package com.lxq.market.service;

import com.lxq.market.model.Category;
import com.lxq.market.util.JDBCUtil;
import com.lxq.market.util.ResultSetConvert;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class CategoryService {

    private static CategoryService categoryServer;
    ResultSetConvert resultSetConvert=ResultSetConvert.getInstance();

    public static CategoryService getInstance() {
        if (categoryServer==null){
            categoryServer=new CategoryService();
        }
        return categoryServer;
    }

    public boolean updateCategory(Category category,String oldCategory){
        JDBCUtil.execSQL("update app set app_category=? where app_category=?",category.getCategoryName(),oldCategory);
        return JDBCUtil.execSQL("update category set category_name=?,category_explain=? where category_name=?",
                category.getCategoryName(), category.getCategoryExplain(), oldCategory);
    }

    public boolean addCategory(Category category){
        return JDBCUtil.execSQL("insert into category values(?,?)", category.getCategoryName(), category.getCategoryExplain());
    }

    public List<Category> getCategory(){
        return resultSetConvert.convert(JDBCUtil.execQuery("select * from category"), Category.class);
    }

    public boolean delete(String categoryName){
        return JDBCUtil.execSQL("delete from category where category_name=?", categoryName);
    }

    public List<String> getCategoryName(){
        ResultSet resultSet = JDBCUtil.execQuery("select * from category");
        return convert(resultSet);
    }

    private List<String> convert(ResultSet resultSet){
        ArrayList<String> convertList;
        if (resultSet==null) {
            return null;
        }
        convertList=new ArrayList<>();
        while (true) {
            try {
                if (!resultSet.next()) break;
                String categoryName = resultSet.getString(resultSet.findColumn("category_name"));
                convertList.add(categoryName);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return convertList;
    }
}
